package com.ls.lserp.modules.setting.web;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.Material;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.service.MaterialService;
import com.ls.lserp.modules.sys.entity.Brand;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.SequenceUtil;

import groovy.util.ResourceException;


/**
  * @ClassName: materialController
  * @Description: 
  * 
  * @author 
  * @date 2017年1月19日 上午10:11:26
  *
  */

@Controller
@RequestMapping(value = "${adminPath}/material/message")
public class MaterialController extends BaseController {
	// 保存 编辑 删除 方法
	@Autowired
	private MaterialService materialService;
	
	
	/**
	  * @Title: get
	  * @Description: 获取我的物料信息
	  * @param @param id
	  * @param @return
	  * @return Material 
	  * @throws
	  */
	
	@ModelAttribute
	public Material get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return materialService.get(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new Material();
		}
	}
	
    /**
      * @Title: list
      * @Description: 查询我的物料一览页面
      * @param @param material
      * @param @param request
      * @param @param response
      * @param @param model
      * @param @return
      * @return String 
      * @throws
      */
	
    @RequiresPermissions("material:stock:view")
    @RequestMapping(value = {"list", ""})
    public String list(Material material, HttpServletRequest request, HttpServletResponse response, Model model) {
    	// 返回页面地址
        return "modules/setting/material";
    }
	
	@RequiresPermissions("material:stock:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(Material material, HttpServletRequest request, HttpServletResponse response, Model model)
			throws ResourceException {
		
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		FileUtils filUtils = new FileUtils();
		
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "material");
		
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		/*searchParam.append("&materialUseType=");
		searchParam.append(material.getMaterialUseType());*/
		searchParam.append("&materialTypeCd=");
		searchParam.append(material.getMaterialTypeCd());
		searchParam.append("&materialNameCn=");
		searchParam.append(material.getMaterialNameCn());
		searchParam.append("&materialColor=");
		searchParam.append(material.getMaterialColor());
		searchParam.append("&materialComposition=");
		searchParam.append(material.getMaterialComposition());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
    	// 当选择定制订单时，可以查询全部和定制订单信息
    	if(StringUtils.isNoneBlank(material.getMaterialUseType())){
    		if(material.getMaterialUseType().equals(ResourcesUtil.getConfig("material_customization"))){
    			material.setMaterialUseType(ResourcesUtil.getConfig("material_all")+","+ResourcesUtil.getConfig("material_customization"));
    		}
    	}
		
    	// 查询一览页面数据
    	Page<Material> page = materialService.findList(new Page<Material>(request, response), material);
		
		// 读取系统路径
		String basePath = SystemPath.getClassPath();
		String tempFilePath = "//"+basePath + "templates//demoHtml//material.txt";
		
		// 读取文件生成字符串
		String materialHtml = readTxtFile(tempFilePath);
		String strHtml = "";
		String strImg = "";
		String strMaterialName="";
		String strCtx = "";
		String strPopup = "";
		int pageNo = 0;
		if (!"".equals(materialHtml)) {
			for (int i = 0; i < page.getList().size(); i++) {
				materialHtml = filUtils.readFileToHtml(tempFilePath);
				// 画面No
				pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
				materialHtml = materialHtml.replace("pageNo", "" + pageNo);
				
				// 照片
				if(StringUtils.isNotEmpty(page.getList().get(i).getFilePath())){
					strImg = "<img src='"+ page.getList().get(i).getFilePath() + "' class='tableImg'>";
				}else{
					strImg = "<img src='" + request.getContextPath() +"/static/images/pic-none.jpg' class='tableImg'>";
				}
				materialHtml = materialHtml.replace("image", "" + strImg);
				
				// 编码/物料名称
		    	if(getLanguage(request).equals("en_us")){
		    		strMaterialName = StringUtils.checkStringNull(page.getList().get(i).getMaterialNameEn());
		    	}else{
		    		strMaterialName = StringUtils.checkStringNull(page.getList().get(i).getMaterialNameCn());
		    	}
		    	materialHtml = materialHtml.replace("materialName", strMaterialName);
		    	materialHtml = materialHtml.replace("materialCode", StringUtils.checkStringNull(page.getList().get(i).getMaterialCode()));
		    	strCtx = request.getContextPath()+Global.getAdminPath();
		    	strPopup = "\"popup('900px','640px','" + strCtx + "/material/message/show?id=" 
				           + page.getList().get(i).getId() + "')\"";
		        // 物料popup
		    	materialHtml = materialHtml.replace("materialIdPopup", strPopup);
		    	
		    	//业务类别
		    	/*materialHtml = materialHtml.replace("materialUseType", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialUseType())));*/
		    	//物料类别
		    	materialHtml = materialHtml.replace("materialTypeCd", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialTypeCd())));
		    	//克重
		    	materialHtml = materialHtml.replace("materialGramWeight", StringUtils.checkStringNull(page.getList().get(i).getMaterialGramWeight()));
		    	//纱织密度
		    	materialHtml = materialHtml.replace("materialThreadCount", StringUtils.checkStringNull(page.getList().get(i).getMaterialThreadCount()));
		    	//物料成分
		    	materialHtml = materialHtml.replace("materialComposition", StringUtils.checkStringNull(page.getList().get(i).getMaterialComposition()));
		    	//物料风格
		    	materialHtml = materialHtml.replace("materialStyle", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialStyle())));
		    	//物料颜色
		    	materialHtml = materialHtml.replace("materialColor", StringUtils.checkStringNull(page.getList().get(i).getMaterialColor()));
		    	//物料织法
		    	materialHtml = materialHtml.replace("materialKnitMethod", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialKnitMethod())));
		    	//幅宽	
		    	materialHtml = materialHtml.replace("materialSpec", StringUtils.checkStringNull(page.getList().get(i).getMaterialSpec()));
		    	materialHtml = materialHtml.replace("materialUnitCd", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialUnitCd())));
		    	//季节年份
		    	materialHtml = materialHtml.replace("materialYear", StringUtils.checkStringNull(page.getList().get(i).getMaterialYear()));
		    	materialHtml = materialHtml.replace("materialSeason", StringUtils.checkStringNull(DictUtils.getDictName(page.getList().get(i).getMaterialSeason())));
		    	//客户
		    	materialHtml = materialHtml.replace("ognizationName", StringUtils.checkStringNull(page.getList().get(i).getOgnizationName()));
		    	
		    	//描述
		    	materialHtml = materialHtml.replace("remarks", StringUtils.checkStringNull(page.getList().get(i).getRemarks()));
				strHtml += materialHtml;
			}
		}
		listMap.put("material", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}

	
	/**
	  * @Title: form
	  * @Description: 新建及编辑我的物料
	  * @param @param material
	  * @param @param redirectAttributes
	  * @param @param model
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("material:stock:edit")
	@RequestMapping(value = "form")
	public String form(Material material,RedirectAttributes redirectAttributes, Model model) {
	    
		if(StringUtils.isBlank(material.getMaterialBarCode())){
			
	        material.setMaterialBarCode(SequenceUtil.materialbarcode().getReturnCode());
	    }
		
		
		
		//将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("material", material);
		
		// 返回页面地址
		return "modules/setting/materialCreate";
	}
	
	
	
	
	/**
	  * @Title: checkName
	  * @Description: 查重
	  * @param @param materialOldCode
	  * @param @param materialCode
	  * @param @return
	  * @return String 
	  * @throws
	  */
	
	@RequiresPermissions("material:stock:edit")
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String oldMaterialCode,String materialCode) {
        try {
        	// 页面获取数据值与旧数据若相同，并且数据值不为null
            if (materialCode != null && materialCode.toUpperCase().equals(oldMaterialCode.toUpperCase())) {
            	// 返回true
                return "true";
            // 页面获取数据值与旧数据若不相同，查询结果为null，并且数据值不为null
            } else if (materialCode != null&& materialService.getByCode(materialCode) == null) {
            	// 返回true
            	return "true";
            }
            // 数据值重名
            return "false";

        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        }
        // 数据值重名
        return "false";
	}
	
	
		
		/**
		  * @Title: save
		  * @Description: 保存数据
		  * @param @param material
		  * @param @param request
		  * @param @param model
		  * @param @param response
		  * @param @return
		  * @return String 
		  * @throws
		  */
		
		@RequiresPermissions("material:stock:edit")
		@RequestMapping(value = "save")
		@ResponseBody
		public String save(Material material,UploadFile  uploadFile, HttpServletRequest request, Model model, HttpServletResponse response ) {
			
			// 判断id是否为null （判断新建或修改）
			if(material.getId()!=null){
				
				// 编辑数据
				// 判断数据是否删除
				Material materialNew=get(material.getId().toString());
	            
				// 判断数据是否删除
				if(materialNew==null || BaseEntity.DEL_FLAG_DELETE.equals(materialNew.getDeleteFlag())){
	                
					// 返回提示信息
					return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	            }
				
			    //排他
			    if(material.getVersion()==get(material.getId().toString()).getVersion()){
			    	
			    	// 版本号加1
			    	material.setVersion(material.getVersion()+1);
			    }else{
			    	
			    	// 返回提示信息
			        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			    }
			}else{
				
				// 新建版本号赋值1
				material.setVersion(1L);
			}
			
			// 保存图片
			if(uploadFile.getFilePath()!=null){
				
	            // 图片来源：1.电脑端 ,2.手机端
				uploadFile.setFileSource(1L);
	            // 所在模块区分（1:需求单 2:款式 3:订单 4:测试 5:工艺图片）
				uploadFile.setModuleKbn(4L);
	            // ftp文件名
				uploadFile.setFtpFile(ResourcesUtil.getConfig("material_picture_url"));
	            
	            // 上传文件路径(以免两个值互相影响)
	            String filePath = uploadFile.getFilePath();
	            // 前台显示路径
	            uploadFile.setShowImgUrl(filePath);
	            // 上传文件路径
	            uploadFile.setFilePath(uploadFile.getFilePath().substring(0,uploadFile.getFilePath().lastIndexOf('/') + 1));
	            // 上传文件
	            uploadFile.setUploadFile(filePath.substring(filePath.lastIndexOf('/') + 1));
	            
	            material.setUploadFile(uploadFile);
			}
			
			
			
			try {
				// 若启用未选择赋值1
				if(material.getEnableFlag()==null){
					material.setEnableFlag("1");
				}
				
			    // 保存我的物料
				materialService.saveMaterial(material);
				
				// 保存成功返回提示信息
		        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "materialSaveSuccess")));
			 } catch (Exception e) {
		           // 记录日志
		           logger.error(e.getMessage(), e);
				// 提示错误信息
				return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		     }
		}
	
    
    /**
      * @Title: show
      * @Description: 查看我的物料
      * @param @param material
      * @param @param model
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("material:stock:view")
    @RequestMapping(value = "show")
    public String show(Material material, Model model) {
    	
    	// 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("material", material);
        
        // 返回页面地址
        return "modules/setting/materialShow";
    }
    
    
    /**
      * @Title: delete
      * @Description: 删除我的物料
      * @param @param material
      * @param @param response
      * @param @return
      * @return String 
      * @throws
      */
    
    @RequiresPermissions("material:stock:edit")
	@RequestMapping(value = "delete")
	public String delete(Material material, HttpServletResponse response) {
		
		    try {
		    	
		    	// 执行逻辑删除方法
		    	materialService.deleteMaterial(material);
            } catch (Exception e) {
                // 记录日志
                logger.error(e.getMessage(), e);
            	// 提示错误信息
                return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
            }
		    
		 // 提示删除成功信息
			return renderString(response,AjaxDone.ok(getText("category_delete_success")));
    }
    
	/**
     * 联动返回城市
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("material:stock:edit")
    @RequestMapping(value = "findOgnization")
    public String findOgnization(Material material,Model model,HttpServletResponse response ) {
    	// 下拉来源机构
    	material.setOgnizationList(materialService.findMaterialOgnizationList(material));
    	model.addAttribute("material",material);
        return "modules/setting/materialCreate";
       
    }
    /**
     * 联动返回城市
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("material:stock:edit")
    @RequestMapping(value = "findBrand")
    public String findBrand(Material material,Model model,HttpServletResponse response ) {
    	Ognization ognization = materialService.getMaterialOgnization(material);
    	
    	// 下拉来源机构
    	model.addAttribute("ognization",ognization);
    	model.addAttribute("material",material);
        return "modules/setting/materialCreate";
       
    }
}
